package com.caichen.scheduler.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.caichen.scheduler.mapper.OrderItemsMapper;
import com.caichen.scheduler.mapper.OrderMapper;
import com.caichen.scheduler.mapper.PartnerBrokerageMapper;
import com.caichen.scheduler.mapper.PartnerLeadMapper;
import com.caichen.scheduler.mapper.PartnerMapper;
import com.caichen.scheduler.mapper.PartnerShopKeeperMapper;
import com.caichen.scheduler.mapper.ProductStockMapper;
import com.caichen.scheduler.params.UpdatePartnerMoneyParams;
import com.caichen.scheduler.pojo.DelayedOrder;
import com.caichen.scheduler.pojo.Order;
import com.caichen.scheduler.pojo.OrderItems;
import com.caichen.scheduler.pojo.Partner;
import com.caichen.scheduler.pojo.PartnerBrokerage;
import com.caichen.scheduler.pojo.PartnerLead;
import com.caichen.scheduler.pojo.PartnerShopKeeper;
import com.caichen.utils.tools.NumberUtils;

@Service
public class OrderService {

	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private PartnerShopKeeperMapper partnerShopKeeperMapper;
	@Autowired
	private PartnerMapper partnerMapper;
	@Autowired
	private PartnerBrokerageMapper partnerBrokerageMapper;
	@Autowired
	private OrderItemsMapper orderItemsMapper;
	@Autowired
	private ProductStockMapper productStockMapper;
	@Autowired
	private PartnerLeadMapper partnerLeadMapper;
	
	
	/**
	 * 获取无退货记录的可做分销数据
	 * @return
	 */
	public List<Order> getNoRefundDistributionList(String dateTime) {
		return orderMapper.getNoRefundDistributionList(dateTime);
	}
	
	/**
	 * 获取有退货记录的可做分销数据
	 * @return
	 */
	public List<Order> getRefundDistributionList(String dateTime) {
		return orderMapper.getRefundDistributionList(dateTime);
	}

	
	/**
	 * 无退货的订单的分销处理业务
	 */
	public void noRefundprocessDistribution(Order order) {
		fxOperation(order, order.getRealAmount());
	}
	
	
	public List<DelayedOrder> findDelayedOrderList( Integer day,Integer orderType){
		return orderMapper.findDelayedOrderList(day, orderType);
	}


	/**
	 * 获取订单未支付超过1小时
	 * @return
	 */
	public List<Order> getOverTimeOrderPay() {
		return orderMapper.getOverTimeOrderPay();
	}
	
	
	public void updateOverTimeOrderPay(Order order) {
		if (order == null) return;
		int row = orderMapper.updateOrderOverTimePay(order.getOrderId());
		if (row <= 0) throw new RuntimeException("Error 更新订单为交易关闭失败！");
		
		List<OrderItems> items = orderItemsMapper.selectDetailsAll(order.getOrderId());
		for (OrderItems item : items) {
			int row_ = productStockMapper.updateStockBySkuAdd(item.getSkuNo(), item.getProductId(), item.getBuyCount());
			if (row_ <= 0) throw new RuntimeException("Error 更新订单为交易关闭， 更新库存数量失败！");
		}
	}


	/**
	 * 有退货的订单的分销处理业务
	 * @param order
	 */
	public void refundProcessDistribution(Order order, double refundAmount) {
		double realAmount = NumberUtils.keepScale(order.getRealAmount() - refundAmount, 2);
		fxOperation(order, realAmount);
	}


	private void fxOperation(Order order, double realAmount) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String date = format.format(new Date());
		if (realAmount > 0) {
			long leadid = 0;
			long followid = 0;
			// 1、根据账号，查询对应的业务人员（一级分销）
			PartnerShopKeeper keeper = partnerShopKeeperMapper.getPartnerKepperForMobile(order.getMemberAccount());
			Partner partner = null;
			if (keeper != null && keeper.getPartner_id() > 0) {
				 partner = partnerMapper.getObjectById(keeper.getPartner_id());
				if (partner != null) {
					double money = NumberUtils.keepScale(realAmount * 0.01, 2);
					if (money > 0) {
						int row = partnerMapper.updateMoney(new UpdatePartnerMoneyParams(partner.getPartner_id(), money));
						if (row <= 0) throw new RuntimeException("Error 更新合伙人员金额失败！");
						int roww = partnerBrokerageMapper.insertObject(new PartnerBrokerage(order.getOrderId(), order.getMemberAccount(), money, date, partner.getPartner_id(), 0, realAmount, keeper.getReal_name()));
						if (roww <= 0) throw new RuntimeException("Error 新合伙人员的流水失败！");
						leadid = partner.getLead_id();
						followid = partner.getFollow_id();
					}
				}
			}
			// 2、根据一级分销员，查询父级业务员（二级分销员）
			if (leadid > 0) {
				PartnerLead partnerLead = partnerLeadMapper.getById(leadid);
				if (partnerLead != null && partnerLead.getStatus() == 0) {
					double money = NumberUtils.keepScale(realAmount * 0.01, 2);
					if (money > 0) {
						int row = partnerLeadMapper.updateMoney(leadid, money);
						if (row <= 0) throw new RuntimeException("Error 更新负责人金额失败！");
						int roww = partnerBrokerageMapper.insertObject(new PartnerBrokerage(order.getOrderId(), order.getMemberAccount(), money, date, leadid, 1, realAmount, keeper.getReal_name()));
						if (roww <= 0) throw new RuntimeException("Error 新负责人的流水失败！");
					}
				}
			}
			// 3、根据二级分销员，查询父级业务员（三级分销员）
			if (followid > 0) {
				PartnerLead follow = partnerLeadMapper.getById(followid);
				if (follow != null && follow.getStatus() == 0) {
					double money = NumberUtils.keepScale(realAmount * 0.03, 2);
					if (money > 0) {
						int row = partnerLeadMapper.updateMoney(followid, money);
						if (row <= 0) throw new RuntimeException("Error 更新跟进人金额失败！");
						int roww = partnerBrokerageMapper.insertObject(new PartnerBrokerage(order.getOrderId(), order.getMemberAccount(), money, date, followid, 1, realAmount, keeper.getReal_name()));
						if (roww <= 0) throw new RuntimeException("Error 新增跟进人的流水失败！");
					}
				}
			}
		}
		// 4、更新订单状态
		int row_ = orderMapper.updateFxState(order.getOrderId());
		if (row_ <= 0) throw new RuntimeException("Error 更新订单分销状态有我！");
	}

	/**
	 * 获取退货订单
	 */
	public double getRefundOrderByOrderNo(String order_no) {
		return orderMapper.getRefundOrderByOrderNo(order_no);
	}
}
